package com.baizhi.serviceimpl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baizhi.annotation.AddCache;
import com.baizhi.annotation.AddLog;
import com.baizhi.annotation.DelCache;
import com.baizhi.dao.UserMapper;
import com.baizhi.entity.User;
import com.baizhi.entity.UserExample;
import com.baizhi.service.UserService;
import com.baizhi.util.AliyunOSSUtil;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.session.RowBounds;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Service("userService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    HttpSession session;

    @AddCache
    @Override
    public HashMap<String, Object> queryByPage(Integer page, Integer rows) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("page",page);

        UserExample example = new UserExample();
        //总条数
        int records = userMapper.selectCountByExample(example);
        map.put("records",records);

        //总页数=总条数/每页展示条数  除不尽+1页
        Integer total = records%rows==0?records/rows:records/rows+1;
        map.put("total",total);
        //数据
        RowBounds rowBounds = new RowBounds((page-1)*rows,rows);

        List<User> users = userMapper.selectByExampleAndRowBounds(example, rowBounds);

        map.put("rows",users);

        return map;
    }

    @DelCache
    @AddLog(description = "添加用户")
    @Override
    @Transactional
    public String add(User user) {
        user.setId(UUID.randomUUID().toString());
        user.setPassword("123456");
        user.setWechat(user.getPhone());
        user.setStatus(1);
        user.setCreateTime(new Date());

        userMapper.insert(user);
        return user.getId();
    }

    @DelCache
    @AddLog(description = "修改用户")
    @Override
    @Transactional
    public String update(User user) {
        userMapper.updateByPrimaryKeySelective(user);
        return user.getId();
    }

    @DelCache
    @AddLog(description = "删除用户")
    @Override
    @Transactional
    public void del(User user) {

        //查询出完整数据
        User delUser = userMapper.selectByPrimaryKey(user.getId());
        System.out.println(delUser);
        //调用工具类删除用户头像
        AliyunOSSUtil.delFile("yingx-dp",delUser.getHeadImg());

        //删除数据库数据
        userMapper.delete(user);
    }

    @Override
    public void uploadUserHeadImg(MultipartFile img, String id) {
        System.out.println(id);
        String realPath = session.getServletContext().getRealPath("/user/img");
        File file = new File(realPath);
        //判断文件夹是否存在
        if(!file.exists()){
            file.mkdirs();
        }
        //获取文件名
        String fileName = UUID.randomUUID().toString()+img.getOriginalFilename();
        //文件上传
        try {
            img.transferTo(new File(realPath,fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //异步操作，对已存在的数据再进行修改
        User user = new User();
        user.setId(id);
        user.setHeadImg(fileName);

        //调用方法执行操作
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public void uploadUserHeadImgAliyun(MultipartFile img, String id) {

        //获取文件名
        String fileName = "photo/"+UUID.randomUUID().toString()+img.getOriginalFilename();
        //文件上传至阿里云

        AliyunOSSUtil.uploadFile("yingx-dp",fileName,img);

        //异步操作，对已存在的数据再进行修改
        User user = new User();
        user.setId(id);
        user.setHeadImg("https://yingx-dp.oss-cn-beijing.aliyuncs.com/"+fileName);
        System.out.println(user);

        //调用方法执行操作
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public void downloadAll(String title,String sheetName,String path) {
        //查询数据库
        List<User> userList = userMapper.selectAll();

        //设置导出的参数  参数：Excel大标题,工作表名
        ExportParams params = new ExportParams(title,sheetName);
        System.out.println(userList);

        //设置工作表参数  参数：导出的参数对象，要导出的集合数据
        Workbook workbook = ExcelExportUtil.exportExcel(params, User.class, userList);

        //导出
        try {
            workbook.write(new FileOutputStream(new File(path)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void downloadThisPage() {

    }

    @AddCache
    @Override
    public HashMap<String, Object> querySexCount() {
        //创建HashMap对象
        HashMap<String, Object> map = new HashMap<>();
        //设置条件
        UserExample example = new UserExample();

        //查询男生人数
        example.createCriteria().andSexEqualTo(1);
        int boy = userMapper.selectCountByExample(example);
        map.put("boy",boy);

        //查询女生人数    总数减去男生人数
        int girl = userMapper.selectCount(null)-boy;
        map.put("girl",girl);

        //返回
        return map;
    }
}
